package com.window24.rest;

import com.google.common.collect.Maps;
import com.window24.command.DemoCommand;
import com.window24.feign.RemoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by yuanfei on 2017/6/5.
 */
@RestController
@RequestMapping(value = "/api/demo")
@Slf4j
public class DemoApi {

    @Value("${foo}")
    private String foo;

    /**
     * 测试Hystrix熔断
     */
    @Resource
    private DemoCommand demoCommand;

    /**
     * 采用Ribbon请求数据
     */
    @Resource
    private RestTemplate restTemplate;

    /**
     * 采用Feign请求数据
     */
    @Resource
    private RemoteService remoteService;

    /**
     * 普通的数据请求, 使用了Hystrix熔断机制
     *
     * @return 字符串/对象
     */
    @RequestMapping(method = RequestMethod.GET, value = "/foo")
    public Object getFoo() {

        Map<String, Object> params = Maps.newHashMap();
        params.put("door", foo);
        log.info("=========走普通数据请求, 使用了Hystrix熔断机制=========");
        return demoCommand.getSomething(params);
    }

    /**
     * 使用Feign远程调用
     *
     * @return 字符串
     */
    @RequestMapping(method = RequestMethod.GET, value = "/feign")
    public String getFeign() {

        log.info("=========使用Feign远程调用请求=========");
        return remoteService.getFoo();
    }

    /**
     * 使用Ribbon请求远程服务，可以自动序列化，这里使用的只是String
     *
     * @return 字符串
     */
    @RequestMapping(method = RequestMethod.GET, value = "/ribbon")
    public String getRibbon() {

        log.info("=========使用Ribbon远程请求=========");
        log.info(restTemplate + ">>");
        return restTemplate.getForObject("http://window24-server/api/demo/foo", String.class);
    }
}